package com.example.wm.utils;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class TsyUtils {
    @Value("${smbm.appsecret}")
    private String appsecreted;
    @Value("${smbm.appId}")
    private String appid;


    String accesstoken = null;

     public void run() {
      long timeInterval = 60000*60*2;// 两小时运行一次
         settoken tos=new settoken();
      Runnable runnable=new Runnable() {
          @Override
            public void run() {
              CloseableHttpClient httpClient = HttpClientBuilder.create().build();
              //响应模型
              CloseableHttpResponse response = null;
              String accessUrl="https://api.weixin.qq.com/cgi-bin/token?appid=wxba6a21693d6b5a99&secret=232661a82ca5a19a24d54db5d7bace0f&grant_type=client_credential";
              while (true){
                  System.out.println("hello");
                  //创建get请求
                  HttpGet httpGet = new HttpGet(accessUrl);
                  try {
                      response = httpClient.execute(httpGet);
                  } catch (IOException e) {
                      throw new RuntimeException(e);
                  }
                  //获取响应实体
                  HttpEntity responseEntity = response.getEntity();
                  String resultDemo = null;
                  try {
                      resultDemo = EntityUtils.toString(responseEntity);
                  } catch (IOException e) {
                      throw new RuntimeException(e);
                  }
                  //转换成对象，好把需要的字段对应的值拿出来
                  JSONObject jsonObject = JSONObject.parseObject(resultDemo);
                  System.out.println(jsonObject);
                  accesstoken= jsonObject.getString("access_token");
                  tos.setToken(accesstoken);


               try{
                      Thread.sleep(timeInterval);
                  }catch (InterruptedException e){
                      e.printStackTrace();
                  }
              }
          }
      };
      Thread thread=new Thread(runnable);
      thread.start();

    }
    public String getnowtime(){
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
        Date date = new Date(System.currentTimeMillis());
        String time = formatter.format(date);
        return time;
    }


    public List<Map> submitOriginalFile(MultipartFile file) throws IOException {
        // 拿取前端标识的文件
        // 获取文件流
        InputStream fileIns = file.getInputStream();
        System.out.println(fileIns+":fileInsfileIns");

        // 获取文件名,中文不乱码写法
//        String name = new String(file.getField("file").getContentDisposition()
//       .getFileName().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        // 将文件流转byte，可作为其他情况存储起来处理
        byte[] fileBytes = InputStreamToByteArray(fileIns);
        // 将byte数组转csv数据
        List<CSVRecord> csvData = byteToCsvFileData(fileBytes);
        // 遍历每一行的数据
        List<Map> list = new ArrayList<>();
        //表头
        List<String> declaredFields = new ArrayList<>();
        for(int j = 0; j < csvData.get(0).size(); j++) {
            declaredFields.add(csvData.get(0).get(j));
            System.out.println("表头：" + csvData.get(0).get(j));
        }
        // 把需要封装的实体类的属性名存入arrayLis
        List<String> arrayList = new ArrayList<>();
        for (int i = 0; i < declaredFields.size(); i++) {
            String name = declaredFields.get(i);
            arrayList.add(name.trim());
        }
        for (int i = 0; i < csvData.size(); i++) {
            Map<String, String> map = new HashMap<>();

            if (  csvData.get(i) != null){
//                System.out.println("每一行数据:" + csvData.get(i));
                for(int j = 0; j < csvData.get(i).size(); j++) {
//                    System.out.println("每一行下每一个单元格数据:" + csvData.get(i).get(j));
                    map.put(arrayList.get(j), csvData.get(i).get(j).trim()); // map 封装
                }
                list.add(map);
            }

        }
        return list;

    }

    /**
     * byte转csv数据
     */
    public List<CSVRecord> byteToCsvFileData(byte[] bytes) {
        List<CSVRecord> records = new ArrayList<>();
        try {
            // 将 byte 数组转为 InputStreamReader 对象
            InputStreamReader in = new InputStreamReader(new ByteArrayInputStream(bytes), "UTF-8");
            // 创建csvParser对象
            CSVFormat csvFormat = CSVFormat.EXCEL;
            CSVParser parser = new CSVParser(in, csvFormat);
            // 读取CSV数据行
            records = parser.getRecords();
            parser.close();
            in.close();
        } catch (Exception e) {
            return null;
        }
        return records;
    }

    /**
     * 文件流转byte
     */
    public byte[] InputStreamToByteArray(InputStream inputStream) {
        try {
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer;
            int len;
            byte[] buf = new byte[2048];
            while ((len = bufferedInputStream.read(buf)) != -1) {
                byteArrayOutputStream.write(buf, 0, len);
            }
            byteArrayOutputStream.flush();
            buffer = byteArrayOutputStream.toByteArray();
            inputStream.close();
            bufferedInputStream.close();
            byteArrayOutputStream.close();
            return buffer;
        } catch (Exception e) {
            return null;
        }
    }


}

